package com.clkj.cldisabledmanclient.util;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.TextView;

import com.clkj.cldisabledmanclient.app.CustomApplication;
import com.clkj.cldisabledmanclient.constant.Config;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.INPUT_METHOD_SERVICE;


/**
 * Created by clboys on 2018/6/21.
 */

public class CommonUtil {


    public static boolean isIdCardNo(String idCardNo, String tipStr)
    {

        if (!IDCardUtil.isIDCard(idCardNo))
        {
            ToastUtil.showShort(CustomApplication.getInstance(),tipStr);
            return false;
        }else {
            return true;
        }


    }
    //简单判断手机号码是否是11位
    public static boolean isMobile(String mobile) {

        boolean flag = false;

        String phoneNumber = mobile.trim();

        if (phoneNumber.length() == 11) {
            flag = true;
        } else {
            flag = false;
        }

        return flag;
    }

    //判断是否是手机号码
    public static boolean isMobile2(String mobile) {

        boolean flag = false;

        if (mobile.length() == 0) {

            return false;

        }

        String[] mobiles = mobile.split(",");

        int len = mobiles.length;

        if (len == 1) {

            return Pattern.matches("^((13[0-9])|(14[5,7,9])|(15[^4,\\D])|(166)|(17[0,1,3,5-8])|(18[0-9])|(19[8|9]))\\d{8}$", mobile);

        } else {

            for (int i = 0; i < len; i++) {

                if (isMobile(mobiles[i])) {

                    flag = true;

                } else {

                    flag = false;

                }

            }

        }

        return flag;

    }

    /**
     * 隐藏键盘
     */
    public static void hideInput(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE);
        View v = activity.getWindow().peekDecorView();
        if (null != v) {
            if (imm != null) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }

    //初始化webview
    @SuppressLint("SetJavaScriptEnabled")
    public static void initWebView(WebView webView) {
        WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本

        // 设置缓存模式,一共有四种模式
        //webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //webSettings.setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式, 将图片调整到合适的大小
        //webSettings.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题

        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setDisplayZoomControls(false);
        webSettings.setAllowFileAccess(true); // 允许访问文件
        webSettings.setBuiltInZoomControls(true); // 设置显示缩放按钮
        webSettings.setSupportZoom(true); // 支持缩放

        webSettings.setSupportMultipleWindows(true);
        //webView.setWebChromeClient(new WebChromeClient());

        //webSettings.setAppCacheEnabled(false);//是否使用缓存
        //webSettings.setDomStorageEnabled(false);//DOM Storage
/**
 * 用WebView显示图片，可使用这个参数 设置网页布局类型： 1、LayoutAlgorithm.NARROW_COLUMNS ：
 * 适应内容大小 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放
 *//**/
        //webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    }

    public static String convertHtmlToNormal(String originalHtml) {
        return originalHtml.replaceAll("&lt;", "<")
                .replaceAll("&gt;", ">")
                .replaceAll("&nbsp;", " ")
                .replaceAll("&amp;", "&")
                .replaceAll("&quot;", "\"");

    }

    //获取文件的类型
    public static String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);

        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        LogUtil.e("fileType:" + contentTypeFor);
        return contentTypeFor;
    }

    /**
     * 从已经有的drawable提取bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitamp(Drawable drawable) {
        BitmapDrawable bd = (BitmapDrawable) drawable;
        Bitmap bitmap = bd.getBitmap();
        return bitmap;
    }


    //将输入流转化为字符串
    public static String getStringFromInputStream(InputStream inputStream) {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer("");
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static String formatNumTwoPointsAfterDots(double number) {
        java.text.DecimalFormat df = new java.text.DecimalFormat("######0.00");
        return df.format(number);
    }

    public static String formatNumOnePointsAfterDots(double number) {
        java.text.DecimalFormat df = new java.text.DecimalFormat("######0.0");
        return df.format(number);
    }

    public static String formatNumNoPointsAfterDots(double number) {
        java.text.DecimalFormat df = new java.text.DecimalFormat("######0");
        return df.format(number);
    }


    //格式化json数据变成类型 Object
    public static Object formatJsonToObject(JsonObject dataObject, String jsonKeyWord, TypeToken aimTypeToken) {
        return new Gson().fromJson(dataObject.get(jsonKeyWord), aimTypeToken.getType());
    }


    //格式话json数据为Object，直接转换json数据，没有key
    public static Object formatJsonToObjectWithNoKey(JsonObject dataObject, TypeToken aimTypeToken) {
        return new Gson().fromJson(dataObject, aimTypeToken.getType());
    }

    //格式化json数据变成类型 list
    public static List formatJsonToList(JsonObject dataObject, String jsonKeyWord, TypeToken aimTypeToken) {
        return new Gson().fromJson(dataObject.get(jsonKeyWord), aimTypeToken.getType());
    }


    //保存对象
    public static void putShareObject(String key, Object object) {
        SPUtils.putObject(CustomApplication.getInstance(), key, object);
    }


    //获取对象
    public static Object getShareObject(String key, Class<Object> clazz) {
        return SPUtils.getObject(CustomApplication.getInstance(), key, clazz);
    }


    //保存常规值 String Integer Boolean Float Long
    public static void putShareValue(String key, Object value) {
        SPUtils.put(CustomApplication.getInstance(), key, value);
    }

    //获取常规值:String Integer Boolean Float Long
    public static Object getShareValue(String key, Object defaultObject) {
        return SPUtils.get(CustomApplication.getInstance(), key, defaultObject);
    }


    //判断两个字符串是否一致
    public static boolean isTwoStrSame(String firstStr, String secondStr, String tip) {
        if (!firstStr.equals(secondStr)) {
            ToastUtil.showShort(CustomApplication.getInstance(), tip);
            return false;
        } else {
            return true;
        }
    }


    public static boolean isListNullOrEmpty(List dataList, String tip) {

        if (dataList == null || dataList.size() == 0) {
            ToastUtil.showShort(CustomApplication.getInstance(), tip);
            return true;

        } else {
            return false;
        }


    }

    //判断某一个对象是否为空
    public static boolean isObjectNull(Object object, String tip) {
        if (null == object) {
            ToastUtil.showShort(CustomApplication.getInstance(), tip);
            return true;
        } else {
            return false;
        }
    }

    public static boolean isEditTextEmpty(EditText editTexes, String tip) {
        if (TextUtils.isEmpty(editTexes.getText().toString())) {
            editTexes.requestFocus();
            ToastUtil.showShort(CustomApplication.getInstance(), tip);
            return true;
        } else {
            return false;
        }
    }

    public static boolean isTextViewEmpty(TextView textView, String tip) {
        if (TextUtils.isEmpty(textView.getText().toString())) {
            if (TextUtils.isEmpty(tip) == false) {
                ToastUtil.showShort(CustomApplication.getInstance(), tip);
            }
            return true;
        } else {
            return false;
        }
    }

    //创建文件基础文件夹
    public static void checkAndCreateBaseFileDirAndDownFileDir() {
        File baseFileDir = null;
        File downFileDir = null;
        if (!FileUtils.checkFileExists(Config.APP_BASE_FOLDER)) {
            baseFileDir = FileUtils.createFile(
                    Environment.getExternalStorageDirectory().getAbsolutePath()
                    , Config.APP_BASE_FOLDER);
        }


        if (!FileUtils.checkFileExists(Config.APP_BASE_FOLDER + Config.FILE_FOLDER_PATH)) {
            downFileDir = FileUtils.createFile(
                    Environment.getExternalStorageDirectory().getAbsolutePath() + Config.APP_BASE_FOLDER
                    , Config.FILE_FOLDER_PATH);
        }

    }

    /**
     * 判断是否为手机号码
     *
     * @param testStr
     * @return
     */
    public static boolean isPhoneNum(String testStr, String tipStr) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";

        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(testStr);
        boolean isMatch = m.matches();

        if (isMatch == false) {
            ToastUtil.showShort(CustomApplication.getInstance(), tipStr);


        }

        return isMatch;
    }

    //判断字符串的长度等于或者大于要求
    public static boolean validateStrLengthEqualRequest(String str, int leastLength, String tipStr) {
        if (str.length() < leastLength) {
            ToastUtil.showShort(CustomApplication.getInstance(), tipStr);
        }

        return str.trim().length() == leastLength;
    }


}
